
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    LeftBar:"",
    LeftLine:null,
    LeftPie:null,
    RightLine:null,
    RightPie:null,
    RightBar:null,
  },
  mutations: {
    sendws(state){
      var websocket = null;
    // state.a=20
    // console.log();
    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("ws://127.0.0.1:8001/websocket/1");
    }
    else{
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
     console.log("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event){
       console.log("open");
    }

    //接收到消息的回调方法
    websocket.onmessage = function(res){
        const data=JSON.parse(res.data)
        state.LeftBar=data.data.LeftBar
        state.LeftLine=data.data.LeftLine
        state.LeftPie=data.data.LeftPie
        state.RightLine=data.data.RightLine
        state.RightPie=data.data.RightPie
        state.RightBar=data.data.RightBar      
    }

    //连接关闭的回调方法
    websocket.onclose = function(){
      
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    }

    }
  },
  actions: {},
  modules: {}
})
